package com.hui.demo.shiro;

import com.hui.demo.shiro.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;

public class DataBaseRealm extends AuthorizingRealm {

    // 用户授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principalCollection) {
        System.out.println("登录成功");
        // 验证通过
        String userName = (String) principalCollection.getPrimaryPrincipal();
        // 获取角色和权限
        Set<String> permissions = new DAO().listPermissions(userName);
        Set<String> roles = new DAO().listRoles(userName);

        // 授权对象
        SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
        // 放入角色权限
        s.setRoles(roles);
        s.setStringPermissions(permissions);
        return s;
    }

    // 用户验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {
        System.out.println("登录");
        // 获取账号密码
        UsernamePasswordToken t = (UsernamePasswordToken)token;
        String userName = token.getPrincipal().toString();
        String password = String.valueOf(t.getPassword());
        // 获取用户
        User user = new DAO().getUser(userName);
        String passwordInDB = user.getPassword();
        String salt = user.getSalt();
        String encodePassword = new SimpleHash("md5", password, salt, 2).toString();
        
        if (null==passwordInDB || !passwordInDB.equals(password)) {
            throw new AuthenticationException();
        }
        // 认证信息存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :databaseRealm
        SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(userName, password, getName());
        return a;
    }
}
